SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE dbo.DnnProduct_PurgeScheduleHistory

AS

DELETE FROM dbo.DnnProduct_ScheduleHistory
FROM dbo.DnnProduct_Schedule s
WHERE (
  SELECT COUNT(*) 
  FROM dbo.DnnProduct_ScheduleHistory sh
  WHERE sh.ScheduleID = DnnProduct_ScheduleHistory.ScheduleID
  AND sh.StartDate >= DnnProduct_ScheduleHistory.StartDate
) > s.RetainHistoryNum
AND s.RetainHistoryNum <> -1
AND s.ScheduleID = DnnProduct_ScheduleHistory.ScheduleID

GO
